<template>
  <page-loading :show="pageLoading">
    <view class="wrap">
      <view class="box">
        <view
          class="photo-box flex flex-jc-sa flex-ai-c"
          v-if="current !== -1 && selected[currentIndex].url"
        >
          <u-swiper
            class="swiper"
            mode="number"
            indicator-pos="bottomLeft"
            :list="imgArr"
            :autoplay="false"
            img-mode="aspectFit"
            :current="currentSwiper"
            name="url"
            bg-color="#fff"
            @click="choosePic"
            @change="swiperChange"
          ></u-swiper>
          <view class="cancel-btn" @click="cancelImg">
            <i-icon icon="iconshanchu-2" type="multiple" size="40rpx"></i-icon>
          </view>
        </view>
        <view class="name">
          <view v-if="current !== -1" class="name-inner">{{
            currentName
          }}</view>
        </view>
        <view
          class="photo flex flex-jc-sa flex-ai-c"
          @click="choosePic"
          v-if="current === -1 || !selected[currentIndex].url"
        >
          <i-icon
            icon="iconxiangji"
            type="single"
            size="50rpx"
            color="#fff"
          ></i-icon>
        </view>
      </view>
      <view class="input-box" v-if="current !== -1">
        <view class="top-input flex">
          <i-icon icon="iconqiyebianji" color="#999" size="34rpx"></i-icon>
          <u-input
            :disabled="current === -1"
            v-model="selected[currentIndex].exceptionMsg"
            type="textarea"
            maxlength="24"
            :auto-height="true"
            placeholder="请输入异常信息"
            placeholder-style="color: #999;"
            class="remark-input"
          />
          <!-- <textarea type="text"   /> -->
        </view>
        <view class="count color-999 font-24"
          >{{ selected[currentIndex].exceptionMsg.length }}/24</view
        >
      </view>
      <view class="box-center">默认正常，如有异常请拍照</view>
      <scroll-view
        :scroll-y="true"
        class="scroll-box"
        :class="current === -1 ? 'scroll-height2' : 'scroll-height'"
      >
        <view class="box-bottom">
          <view
            class="item flex flex-ai-c"
            :class="{ active: index === current }"
            v-for="(item, index) in options"
            @click="chooseItem(index)"
            :key="index"
          >
            <text class="flex-1">{{ item.name }}</text>
            <text
              class="item-status"
              :class="
                selected[index].detection_State === 0
                  ? 'item-status-active'
                  : ''
              "
              @click="changeStatus(index, 0)"
              >未检查</text
            >
            <text
              class="item-status"
              :class="
                selected[index].detection_State === 1
                  ? 'item-status-active'
                  : ''
              "
              @click="changeStatus(index, 1)"
              >无</text
            >
            <text
              class="item-status"
              :class="
                selected[index].detection_State === 2
                  ? 'item-status-active'
                  : ''
              "
              @click="changeStatus(index, 2)"
              >有</text
            >
          </view>
        </view>
      </scroll-view>
      <view class="btn">
        <button class="btn-primary" @click="next">保存并进入下一步</button>
      </view>
    </view></page-loading
  >
</template>
<script>
export default {
  data() {
    return {
      current: -1,
      options: [],
      selected: [], // //已选项目
      id: '', //总类目id
      name: '', //总类目名称
      orderId: '', //到店单id
      technicianName: '', //技师名字
      checkStatus: 0,
      back: 0, //是否显示关闭按钮 0 不显示 1 返回到店单详情的步数
      backPress: true, //是否出页面返回上一页事件
      imgArr: [], //轮播图片
      currentSwiper: 0,
      pageLoading: false, //初始化加载效果
    }
  },

  computed: {
    currentName() {
      if (this.current !== -1) {
        return this.options[this.current].name
      }
      return ''
    },

    currentIndex() {
      if (this.current !== -1) {
        return this.current
      }
      return 0
    },
  },

  onLoad(e) {
    this.backPress = true
    this.orderId = e.id
    this.technicianName = e.name ? e.name : ''
    this.visualCheckData()
    this.back = e.back ? Number(e.back) : 0
  },

  onBackPress() {
    if (this.backPress) {
      if (this.back === 1) {
        uni.redirectTo({
          url:
            '/pages_afterSales/visualCheck/visualCheckMeter?back=1&id=' +
            this.orderId,
        })
        return true
      }
    }
    return false
  },

  onNavigationBarButtonTap() {
    this.backPress = false
    uni.navigateBack({
      delta: 1,
    })
  },

  methods: {
    //获取选项
    getOptions() {
      this.$api.jsonData
        .getVisualOther()
        .then((res) => {
          this.options = res.data[0].list
          this.id = res.data[0].id
          this.name = res.data[0].name
          if (!this.selected.length) {
            for (let i = 0; i < res.data[0].list.length; i++) {
              this.selected.push({
                car_Detection_Typedata_Id: res.data[0].list[i].id, //检测项id
                car_Detection_Typedata_Name: res.data[0].list[i].name, //检测项名称
                url: '', //异常图片地址,
                car_Detection_Typedata_Type_Id: this.id, //上级id
                car_Detection_Typedata_Type_Name: this.name, //上级名称
                detection_State: 1, //状态（0未检测，1正常，2异常）
                exceptionMsg: '', //备注说明
              })
            }
          }
          this.pageLoading = true
        })
        .catch((err) => {
          console.log(err)
          this.pageLoading = true
        })
    },

    //数据回显
    visualCheckData() {
      this.$api.afterSales
        .visualCheckData({
          order_arrive_store_id: this.orderId,
          detection_Type: 3, //检测类型(0预检外观,1预检内饰,2预检仪表盘,3预检其它检查)
        })
        .then((res) => {
          console.log(res.data)
          if (res.data.length) {
            this.selected = [...res.data]
            this.imgArr = res.data.filter((item) => {
              return item.detection_State === 2
            })
          }
          this.getOptions()
        })
        .catch((e) => {
          console.log(e)
          this.getOptions()
        })
    },
    //选择
    chooseItem(index) {
      if (this.current === index) {
        // this.current = -1
      } else if (this.current !== -1) {
        if (
          this.selected[this.current].detection_State === 2 &&
          !this.selected[this.current].url
        ) {
          uni.showToast({
            title: `请上传[${this.currentName}]的异常图片`,
            duration: 3000,
            icon: 'none',
          })
          return
        } else {
          this.current = index
        }
      } else {
        this.current = index
      }
      for (let i = 0; i < this.imgArr.length; i++) {
        if (
          this.selected[index].car_Detection_Typedata_Id ===
          this.imgArr[i].car_Detection_Typedata_Id
        ) {
          this.currentSwiper = i
        }
      }
    },

    //删除图片
    cancelImg() {
      this.$set(this.selected[this.current], 'url', '')
      this.imgArr = this.selected.filter((item) => {
        return item.detection_State === 2
      })
      uni.showToast({
        title: '图片已删除',
        icon: 'none',
      })
    },

    //滑动
    swiperChange(index) {
      for (let i = 0; i < this.selected.length; i++) {
        if (
          this.selected[i].car_Detection_Typedata_Id ===
          this.imgArr[index].car_Detection_Typedata_Id
        ) {
          this.current = i
        }
      }
    },

    //修改检查状态
    changeStatus(i, data) {
      if (this.current !== -1 && this.current !== i) {
        if (
          this.selected[this.current].detection_State === 2 &&
          !this.selected[this.current].url
        ) {
          uni.showToast({
            title: `请上传[${this.currentName}]的异常图片`,
            duration: 3000,
            icon: 'none',
          })
          return
        } else {
          this.current = i
        }
      } else {
        this.current = i
      }
      console.log(this.selected[i])
      this.$set(this.selected[i], 'detection_State', data)
      if (data !== 2) {
        this.$set(this.selected[i], 'url', '')
      }
      this.imgArr = this.selected.filter((item) => {
        return item.detection_State === 2
      })
    },

    //下一步
    next() {
      if (
        this.current !== -1 &&
        this.selected[this.current].detection_State === 2 &&
        !this.selected[this.current].url
      ) {
        uni.showToast({
          title: `请上传[${this.currentName}]的异常图片`,
          duration: 3000,
          icon: 'none',
        })
        return
      }

      this.$api.afterSales
        .addVisualCheck({
          order_arrive_store_id: this.orderId,
          technician_name: this.technicianName,
          detection_Type: 3, //检测类型(0预检外观,1预检内饰,2预检仪表盘,3预检其它检查)
          list: this.selected,
        })
        .then((res) => {
          uni.showToast({
            title: '提交成功',
            duration: 2000,
          })
          this.$store.commit('afterSales/setSignData', {
            id: this.orderId,
            type: 0, //0预检,1上检测，2质检交车报告
            figure: 0, //0技师，1客户
          })
          const param = JSON.stringify({
            type: 'before',
            count: 2,
            fnName: 'arrvialOrderSign',
          })
          const data = JSON.stringify({
            type: 'after', // before为回退页面， after为下一页
            url:
              '/pages_afterSales/orderConfirm/customerConfirm?typeOptions=' +
              param, // 下一页的页面路径
            fnName: 'arrvialOrderSign', //接口
          })
          setTimeout(() => {
            uni.redirectTo({
              url:
                '/pages_afterSales/signature/signature?back=1&title=技师签字&typeOptions=' +
                data,
            })
          }, 2000)
        })
        .catch((e) => {
          console.log(e)
        })
    },

    //上传图片
    choosePic() {
      if (this.current === -1) {
        uni.showToast({
          title: '请选择异常项目',
          duration: 2000,
          icon: 'none',
        })
        return
      }
      const _this = this
      uni.showActionSheet({
        itemList: ['拍照', '打开相册'],
        success(res) {
          const cameraType = res.tapIndex ? 'album' : 'camera'
          uni.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [cameraType], // 从相册选择
            success: function (result) {
              uni.showLoading({
                title: '图片上传中~',
              })
              _this.$api.files
                .uploadImg({
                  filePath: result.tempFilePaths[0],
                })
                .then((res) => {
                  _this.$set(
                    _this.selected[_this.current],
                    'url',
                    res.baseUrl + res.url
                  )
                  _this.$set(
                    _this.selected[_this.current],
                    'detection_State',
                    2
                  )
                  _this.imgArr = _this.selected.filter((item) => {
                    return item.detection_State === 2
                  })
                  for (let i = 0; i < _this.imgArr.length; i++) {
                    if (
                      _this.selected[_this.current]
                        .car_Detection_Typedata_Id ===
                      _this.imgArr[i].car_Detection_Typedata_Id
                    ) {
                      _this.currentSwiper = i
                    }
                  }
                  uni.hideLoading()
                })
                .catch((err) => {
                  uni.hideLoading()
                  uni.showToast({
                    title: '图片上传失败，请稍后重试',
                    icon: 'none',
                  })
                })
            },
          })
        },
      })
    },
  },
}
</script>
<style lang="scss" scoped>
page {
  background: #f6f6f6;
}
.wrap {
  padding-top: 20rpx;
  background: #f6f6f6;

  .box {
    position: relative;
    height: 240rpx;
    background: #ffffff;
    border-radius: 10rpx;
    text-align: center;
    margin: 0 24rpx;

    .name {
      position: absolute;
      top: 0;
      width: 100%;
      text-align: center;
      height: 44rpx;
      margin: 16rpx auto;

      .name-inner {
        display: inline-block;
        min-width: 140rpx;
        padding: 0 20rpx;
        height: 44rpx;
        line-height: 44rpx;
        background: rgba(255, 226, 62, 0.5);
        border-radius: 22rpx;
        font-size: 24rpx;
        font-weight: 500;
        color: #333333;
        text-align: center;
      }
    }

    .photo {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -44rpx;
      margin-top: -44rpx;
      width: 88rpx;
      height: 88rpx;
      border-radius: 50%;
      background: #888;
    }

    .photo-box {
      position: relative;
      height: 240rpx;

      .img {
        width: 100%;
        height: 240rpx;
      }

      .cancel-btn {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 99;
        padding: 10rpx 10rpx 0;
      }

      .swiper {
        width: 100%;
        height: 240rpx;
      }
    }
  }

  // 备注建议
  .input-box {
    margin: 16rpx 24rpx 19rpx;
    padding: 12rpx 20rpx;
    border-radius: 10rpx;
    background: #fff;

    .i-icon {
      margin: 16rpx 10rpx 0 0;
    }

    .remark-input {
      font-size: 28rpx;
    }

    .count {
      text-align: right;
    }
  }

  .box-center {
    height: 50rpx;
    line-height: 50rpx;
    background: #fff6e0;
    font-size: 26rpx;
    font-weight: bold;
    color: #fbb000;
    padding-left: 24rpx;
    margin: 20rpx 0;
  }

  .scroll-height2 {
    height: calc(100vh - 475rpx);
  }

  .scroll-height {
    height: calc(100vh - 575rpx);
  }

  .scroll-box {
    padding: 0 35rpx;

    .item {
      height: 110rpx;
      padding-left: 24rpx;
      padding-right: 24rpx;
      background: #ffffff;
      border: 3rpx solid transparent;
      border-radius: 10rpx;
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
      margin: 10rpx 10rpx 20rpx;

      .item-status {
        height: 60rpx;
        line-height: 60rpx;
        width: 130rpx;
        text-align: center;
        border-radius: 30rpx;
        background: #f6f6f6;
        margin-left: 20rpx;
      }

      .item-status-active {
        background: #ffe23e;
      }
    }

    .active {
      border-color: #fbb000;
      box-shadow: 4rpx 6rpx 8rpx 0 rgba(0, 0, 0, 0.2);
    }
  }

  .btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16rpx 24rpx;
    background: #fff;

    .btn-primary {
      width: 100%;
    }
  }
}

/deep/ uni-button:after {
  border: none;
}
/deep/ uni-radio .uni-radio-input.uni-radio-input-checked:before {
  color: #000;
}
</style>
